#!/usr/bin/env python
# -*- coding: utf-8 -*-


class DataHandle(object):

    @classmethod
    def dfloat_handle(cls, data):
        """
        处理通信协议中的IEEE754双精度浮点数
        :param data: 获得的十六进制数据
        :return: 实际数据
        """
        # 将十六进制转为二进制字符串方便处理
        data_int = int.from_bytes(data, byteorder='big', signed=True)
        data_bin = bin(data_int).replace('0b', '').zfill(64)
        # 转为十进制整数方便计算
        S = int(data_bin[0], 2)
        E = int(data_bin[1:12], 2)
        M = int(data_bin[12:], 2)
        real_data = 2 ** (E - 1023) * (1 + (M / 4503599627370496))  # 这一串数字是2 ** 52
        return real_data if S == 0 else -1 * real_data

    @classmethod
    def sfloat_handle(cls, data):
        """
        处理通信协议中的IEEE754单精度浮点数
        :param data: 获得的十六进制数据
        :return: 实际数据
        """
        data_int = int.from_bytes(data, byteorder='big', signed=True)
        data_bin = bin(data_int).replace('0b', '').zfill(32)
        S = int(data_bin[0], 2)
        E = int(data_bin[1:9], 2)
        M = int(data_bin[9:], 2)
        real_data = 2 ** (E - 127) * (1 + (M / 8388608))  # 这一串数字是2 ** 23
        return real_data if S == 0 else -1 * real_data

    @classmethod
    def bcd_date(cls, data):
        """
        BCD转化时间
        :param data:
        :return:
        """
        timelist = [i.replace('0x', '') for i in data]
        year = '20' + timelist[0]
        month = timelist[1].zfill(2)
        day = timelist[2].zfill(2)
        hour = timelist[3].zfill(2)
        minute = timelist[4].zfill(2)
        second = float(timelist[5].zfill(2))
        return '%s-%s-%s %s:%s:%f' % (year, month, day, hour, minute, second)

    @classmethod
    def hex_data(cls, data):
        """
        十六进制状态码
        :param data:
        :return:
        """
        timelist = [hex(i).replace('0x', '').zfill(2) for i in data]
        return ''.join(timelist)

    @classmethod
    def int_data(cls, data):
        """
        INT型数据
        :param data:
        :return:
        """
        return data
